const sysVoice = wx.createInnerAudioContext(), myVoice = wx.createInnerAudioContext();
import commonAPI from '../../api/api'
const FN = require('../../utils/public');
Page({

  // 页面的初始数据
  data: {
    loadingEnd: "none",
    mode: "1", // 1代表自己，2代表观察者模式
    correctRecordArr: [],
    hasPlaying: true,
    myvoiceplaying: true,
    teaVoicePlaying: true,
    userInfo: {}, //用户信息
    voiceInfoItem: {}, //单独音频对象
    myvoiceInfo: [], //
    options: {},
    currURL: '',
    vrInfoObj: [],
    show2: false,
    buttons2: [{
      type: 'primary',
      className: 'getIntgral',
      text: '获取积分',
      value: 1
    }],
    cutJFNum: 30,
    integral: {}, // 积分
    tipword: '',
    currTeacherCorrect: {},
    // rewardList: [],// 评分
    reward: {},
    evadingAudit: {}
  },

  //生命周期函数--监听页面加载
  onLoad: function (options) {
    var that = this;
    wx.hideShareMenu(); // 禁止分享
    that.setData({
      options: options
    })
    that.init();
  },

  init: function () {
    var options = this.data.options;
    if (options.hasOwnProperty('correctRecordBatch')) { // 服务通知消息进入
      this.fetchCorrectVoiceList('batch', options.correctRecordBatch);
    }
    if (options.hasOwnProperty('vrid')) { // 我的纠音记录进入
      this.fetchCorrectVoiceList('vrid', options.vrid);
    }
    if (options.hasOwnProperty('mode')) { // 纠音集进入
      this.setData({
        mode: options.mode
      })
    }
  },
  
  // 查询老师纠音集
  fetchCorrectVoiceList: function (type, queryParam) {
    var params = type === 'batch' ? { correctRecordBatch: queryParam } : { voiceResultId: queryParam };
    commonAPI.getCorrectRecordByBatch(params).then(res => {
      if (res.code == '200') {
        this.dealData(res);
      }
    })
  },

  // 封装数据
  dealData: function (res) {
    var that = this;
    var correctRecordObj = res.data.correctRecord;
    var voiceToen = "voiceInfoItem.voiceToen";
    var EnTozh = "voiceInfoItem.EnTozh";
    var voiceResultInfo = "voiceInfoItem.voiceResultInfo";
    var voiceSystemImage = "voiceInfoItem.voiceSystemImage";
    var voiceSystemURL = "voiceInfoItem.voiceSystemURL";
    var vrId = "voiceInfoItem.voiceResultId";
    var timing = "voiceInfoItem.timing";
    var endTiming = "voiceInfoItem.endTiming";
    var voiceFileType = "voiceInfoItem.voiceFileType";
    that.setData({
      loadingEnd: 'block',
      integral: res.data.integral.length > 0 ? res.data.integral[0] : {},
      [timing]:correctRecordObj[0].timing,
      [endTiming]:correctRecordObj[0].endTiming,
      [voiceFileType]:correctRecordObj[0].voiceFileType,
      [voiceToen]: correctRecordObj[0].voiceToen,
      [voiceResultInfo]: correctRecordObj[0].voiceResultInfo,
      [EnTozh]: correctRecordObj[0].enTozh,
      [voiceSystemImage]: correctRecordObj[0].voiceSystemImage,
      [voiceSystemURL]: correctRecordObj[0].voiceSystemURL,
      vrInfoObj: correctRecordObj,
      [vrId]: correctRecordObj[0].voiceResultId
    })
    that.replyToStudentRecord(correctRecordObj);
    // that.rewardList(that.data.vrInfoObj[0].wdTeacherId);
  },

  // 查询老师的打赏记录
  // rewardList: function (teacherId) {
  //   var that = this;
  //   commonAPI.getRewardRecordListByTeacherId({ wdTeacherId: teacherId }).then(res => {
  //     if (res.code == '200') {
  //       that.setData({
  //         rewardList: res.data.RRlist,
  //         reward: res.data.reward
  //       })
  //     }
  //   })
  // },

    // 播放原音 originalvoiceurl
    playOriginalVoice: function () {
      if (this.data.voiceInfoItem.voiceFileType == '2') {
        this.playSMvoiceFile(this.data.voiceInfoItem);// 播放小音频
      } else {
        this.playVoiceByTimes(this.data.voiceInfoItem);// 播放时间段模式
      }
    },

  // 播放原音
  playSMvoiceFile: function (voiceInfoItem) {
    var that = this;
    that.stopAllVoice();
    sysVoice.onError((res) => {
      // 播放音频失败的回调
      that.setData({
        hasPlaying: true
      })
    })
    sysVoice.src = voiceInfoItem.voiceSystemURL;
    sysVoice.play();
    sysVoice.onPlay(function () {
      wx.showLoading({
        title: '播放中···',
      })
      that.setData({
        hasPlaying: false, // 播放中
        currURL:voiceInfoItem.voiceSystemURL
      })
    });

    // 音频暂停回调
    sysVoice.onStop(function () {
      that.setData({
        hasPlaying: true
      })
    });

    // 音频结束回调
    sysVoice.onEnded(function () {
      FN.LoadingOff();
      that.setData({
        hasPlaying: true
      })
    });
  },

   // 播放音频按照时间段，新方法
   playVoiceByTimes(obj) {
    
    wx.showLoading({
      title: '播放中···',
    })
    var that = this;
    const bam = wx.getBackgroundAudioManager();
    const star = parseFloat(obj.timing);
    const end = parseFloat(obj.endTiming);
    bam.src = obj.voiceSystemURL
    bam.title = obj.voiceToen
    bam.epname = obj.voiceToen// 专辑名，原生音频播放器中的分享功能，分享出去的卡片简介，也将使用该值
    bam.singer = obj.voiceToen
    bam.coverImgUrl = obj.voiceSystemImage
    bam.startTime = star;
    bam.play();
    bam.onPlay(function () {
      that.setData({
        hasPlaying: false, // 播放中
        currURL:obj.voiceSystemURL
      })
      setTimeout(() => {
        bam.stop()
      }, (end - star) * 1000);
    })
    bam.onError(function () {
      bam.stop()
      that.setData({
        hasPlaying: true
      })
      wx.hideLoading();
    })

    // 暂停
    bam.onStop(function () {
      wx.hideLoading();
      that.setData({
        hasPlaying: true
      })
    })

    // 播放结束
    bam.onEnded(() => {
      bam.stop()
      FN.LoadingOff();
      that.setData({
        hasPlaying: true
      })
    })
  },

  // 暂停原音
  stopSysVoice: function () {
    var that = this;
    sysVoice.pause();
    sysVoice.onPause(function () {
      FN.LoadingOff();
      that.setData({
        hasPlaying: true
      })
    })
  },

  // 播放自己的语音
  playMyvoice: function (e) {
    var that = this,
      vrJson = e.currentTarget.dataset.myvoiceurl;
    var vrObj = JSON.parse(vrJson);
    that.stopAllVoice();
    myVoice.onError((res) => {
      // 播放音频失败的回调
      FN.LoadingOff();
      that.setData({
        myvoiceplaying: true
      })
    })
    myVoice.src = vrObj.tempFilePath;
    myVoice.play();
    myVoice.onPlay(function () {
      FN.Loading(true, '播放中···')
      that.setData({
        myvoiceplaying: false,
        currURL: vrObj.tempFilePath
      })
    });
    // 音频暂停回调
    myVoice.onStop(function () {
      FN.LoadingOff();
      that.setData({
        myvoiceplaying: true
      })
    });
    // 音频结束回调
    myVoice.onEnded(function () {
      FN.LoadingOff();
      that.setData({
        myvoiceplaying: true
      })
    });
  },

  // 老师的语音播放 先判断是否有预约，有预约就不扣积分，否则扣积分
  playTeaVoice: function (e) {
    var i = e.currentTarget.dataset.index,
      that = this;
    const crObj = that.data.correctRecordArr[i];
    that.setData({
      currTeacherCorrect: crObj
    })
    if (that.data.mode == '2') {
      that.playTeacherVoice(i, crObj); // 播放老师语音
    } else {
      // 满足3个条件之一：1.之前有预约过（消耗过积分）2.该语音已经收听过  3.已经消耗积分 4.该条纠音老师设置不需要消耗积分
      if (crObj.hasOwnProperty('beforehandAppointmentStatus') || crObj.pushMsgRecordStatus == '3' || crObj.hasConsumeIntegral == '1' || crObj.hasConsumeIntegral == '-1') {
        FN.Loading(true, '播放中···')
        that.playTeacherVoice(i, crObj); // 播放老师语音
      } else {
        if (that.data.integral.integralNum < that.data.cutJFNum) { // 积分不足
          that.setData({ // 弹出积分不足提醒，
            tipword: "当前积分不足，请补充积分",
            show2: true
          })
        } else { // 积分充足，自动扣除积分 然后再播放语音
          that.upateConsumeIntegralStatus(i, crObj); // 更新是否消耗积分
        }
      }
    }
  },

  // tool 老师语音播放方法
  playTeacherVoice: function (i, crObj) {
    var that = this;
    if (that.data.mode == '1') {
      that.updateCRStatus(crObj.pushMsgRecordId);
    }
    var pushMsgRecordStatus = "correctRecordArr[" + i + "].pushMsgRecordStatus";
    that.setData({
      [pushMsgRecordStatus]: '3'
    })
    that.stopAllTeaVoice();
    var teaVoicePlaying = "correctRecordArr[" + i + "].teaVoicePlaying";
    that.stopAllVoice();
    that.teaVoice = wx.createInnerAudioContext();
    that.teaVoice.onError((res) => {
      // 播放音频失败的回调
      that.setData({
        [teaVoicePlaying]: false
      })
    })
    that.teaVoice.src = crObj.correctVoiceUrl;
    that.teaVoice.play();
    that.teaVoice.onPlay(function () {
      that.setData({
        [teaVoicePlaying]: false,
        currURL: crObj.correctVoiceUrl
      })
    });

    // 音频暂停回调
    that.teaVoice.onStop(function () {
      FN.LoadingOff();
      that.setData({
        [teaVoicePlaying]: true
      })
    });

    // 音频结束回调
    that.teaVoice.onEnded(function () {
      FN.LoadingOff();
      that.setData({
        [teaVoicePlaying]: true
      })
    });
  },

  // 播放前暂停所有音频
  stopAllVoice: function () {
    var that = this;
    sysVoice.stop();
    myVoice.stop();
    if (that.teaVoice != null) {
      that.teaVoice.stop();
    }
  },

  // html解析成小程序码
  stopAllTeaVoice: function () {
    var that = this,
      a = that.data.correctRecordArr,
      temarr = new Array();
    let res = a.map((item, i, arr) => {
      item.teaVoicePlaying = true;
      temarr.push(item);
    })
    that.setData({
      correctRecordArr: temarr
    })
  },

  // 同意消耗积分播放语音
  getIntgral: function (e) {
    var that = this;
    if (e.detail.item.value == 1) { // 查看积分规则
      that.rule();
    }
    that.setData({
      show2: false
    })
  },

  // 修改纠音记录表：状态，记录已消耗积分，同时积分记录表更新 
  upateConsumeIntegralStatus: function (i, crObj) {
    var that = this;
    commonAPI.updateHasConsumeIntegral({ correctRecordBatch: that.data.correctRecordArr[0].correctRecordBatch }).then(res => {
      if (res.code == '200') {
        FN.Toast('扣除4积分')
        that.playTeacherVoice(i, crObj); // 播放老师语音
        that.getIntegral(); // 更新积分
        that.updateHasConsumeIntegral(); // 本地更新所有积分消耗状态为1

      }
    })
  },

  // 本地更新所有积分消耗状态为1
  updateHasConsumeIntegral: function () {
    var that = this,
      tmparr = new Array();
    that.data.correctRecordArr.map(function (item, index, arr) {
      item.hasConsumeIntegral = '1';
      tmparr.push(item);
    })
    that.setData({
      correctRecordArr: tmparr
    })
  },

  // 积分规则
  rule: function () {
    wx.navigateTo({
      url: '../myIntegral/myIntegral'
    })
  },

  // html解析成小程序码
  replyToStudentRecord: function (d) {
    var that = this
     d.map((item, i, arr) => {
      item.teaVoicePlaying = true
    })
    that.setData({
      correctRecordArr: d
    })
  },

  // 修改状态  
  updateCRStatus: function (id) {
    var that = this;
    if (that.data.currTeacherCorrect.pushMsgRecordStatus != "3") { // 已经收听就不再更改状态
      commonAPI.updateCRStatus({
        pushMsgRecordStatus: '3',
        pushMsgRecordId: id,
        "voiceResultId": that.data.voiceInfoItem.voiceResultId
      }).then(res => {
        
      })
    }
  },

  // 再次跟读
  againRepeat: function () {
    var that = this;
    wx.navigateTo({
      url: '../homeworkrepeat/homeworkrepeat',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { scene: that.data.vrInfoObj[0].voiceSystemId })
      }
    })
  },

  // 查询积分剩余
  getIntegral: function () {
    var that = this;
    commonAPI.surplusIntegral({}).then(res => {
      if (res.code == '200') {
        that.setData({
          integral: res.data
        })
      }
    })
  },

  // 打开评分板 查询是否已经评分
  openPraiseServer: function () {
    var that = this;
    FN.Loading('跳转中···')
    wx.navigateToMiniProgram({
      appId: 'wxbf6140c14ee1b85c',
      path: 'pages/reward/reward?teacherName=' + that.data.vrInfoObj[0].wdTeacherName + "&correctOpenId=" + that.data.integral.openId + "&wdTeacherId=" + that.data.vrInfoObj[0].wdTeacherId + "&rewardId=" + that.data.reward.rewardId + "&correctRecordBatch=" + that.data.vrInfoObj[0].correctRecordBatch,
      extraData: {
        correctOpenId: that.data.integral.openId,
        wdTeacherId: that.data.vrInfoObj[0].wdTeacherId,
        teacherName: that.data.vrInfoObj[0].wdTeacherName,
        rewardId: that.data.reward.rewardId,
        correctRecordBatch: that.data.vrInfoObj[0].correctRecordBatch
      },
      envVersion: 'release', // develop	开发版	trial	体验版	release	正式版	
      success(res) {
        // 打开成功
        console.log("打开成功");
      },
      fail: function () {
        console.log("打开fail");
      },
      complete: function () {
        FN.LoadingOff();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    this.setData({
      voiceInfoItem: {}, //单独音频对象
      voiceInfoItem: this.data.correctRecordArr[0],
      myvoiceInfo: []
    });
    if (that.data.vrInfoObj.length > 0) {
      // that.rewardList(that.data.vrInfoObj[0].wdTeacherId);
    }
    this.getIntegral();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("生命周期函数--监听页面卸载");
    this.stopAllVoice();
  },
})